package com.itheima.appserver.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.appserver.excepiton.MyException;
import com.itheima.appserver.interceptor.UserThreadLocal;
import com.itheima.commons.autoconfig.template.AipFaceTemplate;
import com.itheima.commons.autoconfig.template.OssTemplate;
import com.itheima.commons.model.domain.Peach;
import com.itheima.commons.model.domain.UserInfo;
import com.itheima.commons.model.vo.ErrorResult;
import com.itheima.dubbo.interfaces.PeachApi;
import com.itheima.dubbo.interfaces.UserInfoApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * UserInfo业务类
 */
@Service
public class UserInfoService {

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private AipFaceTemplate faceTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    @Reference
    private PeachApi peachApi;

    /**
     * 完善个人信息
     *
     * @param params
     */
    public void loginReginfo(Map<String, String> params) {
        // 判断参数是否合法
        // 四个参数必须都不为空
        if (StrUtil.hasBlank(params.get("gender"), params.get("nickname"), params.get("birthday"), params.get("city"))) {
            throw new MyException(ErrorResult.paramesIsEmpty());
        }

        // 如果都不为空 调用Dubbo服务插入到数据库中 UserInfo
        userInfoApi.addUserInfo(UserInfo.builder()
                .userId(UserThreadLocal.getUserId())
                .nickName(params.get("nickname"))
                .birthday(params.get("birthday"))
                .city(params.get("city"))
                .sex(params.get("gender").equalsIgnoreCase("man") ? 1 : 2)
                .created(new Date())
                .build());
    }

    /**
     * 上传用户头像
     *
     * @param headPhoto
     */
    public void loginReginfoHead(MultipartFile headPhoto) {
        // 校验文件的格式
        // png  jpg jpeg  abcpng
        if (!StrUtil.endWithAnyIgnoreCase(headPhoto.getOriginalFilename(), ".png", ".jpg", ".jpeg")) {
            throw new MyException(ErrorResult.picFormatIncorrect());
        }
        // 校验文件的大小
        if ((headPhoto.getSize() / 1024 / 1024) >= 2) {
            throw new MyException(ErrorResult.picSizeIncorrect());
        }

        // 校验人脸
        try {
            if (!faceTemplate.detectFace(headPhoto.getBytes())) {
                throw new MyException(ErrorResult.picFormatIncorrect());
            }
            // 上传到阿里云OSS  返回地址
            String pictureURL = ossTemplate.uploadPicture(headPhoto.getBytes(),
                    StrUtil.subAfter(headPhoto.getOriginalFilename(), ".", true));
            // 把地址更新到MYSQL数据库
            userInfoApi.updateLogo(UserThreadLocal.getUserId(), pictureURL);
        } catch (IOException e) {
            throw new MyException(ErrorResult.picFormatIncorrect());
        }
    }

    /**
     * 根据用户的ID查询用户的信息
     *
     * @param userId
     * @return
     */
    public UserInfo findUserInfoByUserId(Long userId) {
        return userInfoApi.findUserInfoByUserId(userId);
    }

    /**
     * 根据用户的id集合查询用户的信息列表
     *
     * @param userInfo 查询条件
     * @param userIds  要查询的用户的id集合
     * @return
     */
    public Map<Long, UserInfo> findUserInfoListByUserIds(UserInfo userInfo, List<Long> userIds) {
        if (ObjectUtil.isEmpty(userInfo)) {
            return userInfoApi.findUserInfoListByUserIds(userIds);
        }
        return userInfoApi.findUserInfoListByUserIds(userInfo, userIds);
    }

    /**
     * 更新用户信息到MySQL中
     *
     * @param userInfo
     */
    public void updateUserInfoByUserId(UserInfo userInfo) {
        // 校验userInfo对象中的数据
        userInfoApi.updateUserInfoByUserId(userInfo);
    }

    public void savePeach(MultipartFile peach) {
        // 校验文件的格式
        // png  jpg jpeg  abcpng
        if (!StrUtil.endWithAnyIgnoreCase(peach.getOriginalFilename(), ".mp3",".CD",".WAVE",",MPEG","m4a")) {
            throw new MyException(ErrorResult.peachFormatIncorrect());
        }
        // 校验文件的大小
        if ((peach.getSize() / 1024 / 1024) >= 10) {
            throw new MyException(ErrorResult.peachSizeIncorrect());
        }

        try {
            //上传到空间/命名没改
            String pictureURL = ossTemplate.uploadPicture(peach.getBytes(),
                    StrUtil.subAfter(peach.getOriginalFilename(), ".", true));
            // 把地址更新到MYSQL数据库
            Peach build = Peach.builder()
                    .created(new Date())
                    .soundUrl(pictureURL)
                    .userId(UserThreadLocal.getUserId())
                    .build();

            peachApi.insertPeach(build);
        } catch (IOException e) {
            throw new MyException(ErrorResult.peachFormatIncorrect());
        }

    }

}
